import React, {HTMLAttributes, useEffect, useRef} from 'react';
import Artplayer from 'artplayer';
import {createStyles} from "antd-style";
import Hls from 'hls.js';
import useThemeStore from "@/store/ThemeStore.ts";

interface Props {
    getInstance: (art: Artplayer) => void
    divProp?: HTMLAttributes<HTMLDivElement>
}

const useStyles = createStyles(({css, token}) => {
    return {
        container: css`
            height: 500px;
            width: 100%;
        `,
    }
})

const App: React.FC<Props> = ({getInstance, divProp}) => {
    const artRef = useRef<HTMLDivElement>(null);
    const theme = useThemeStore(state => state.theme)
    const {styles} = useStyles()

    useEffect(() => {
        if (artRef.current == null) {
            return
        }
        const art = new Artplayer({
            url: "",
            autoplay: false,
            container: artRef.current,
            theme: "#" + theme.color,
            pip: true,
            fullscreen: true,
            fullscreenWeb: true,
            fastForward: true, // 移动端长按倍速播放
            autoOrientation: true, // 移动端自动旋转播放器
            screenshot: true, // 截图按钮
            customType: {
                ts: (video, url, art) => {
                    if (Hls.isSupported()) {
                        if (art.hls) art.hls.destroy();
                        const hls = new Hls();
                        hls.loadSource(url);
                        hls.attachMedia(video);
                        art.hls = hls;
                        art.on('destroy', () => hls.destroy());
                    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
                        video.src = url;
                    } else {
                        art.notice.show = 'Unsupported playback format: m3u8';
                    }
                },
            },
        });

        if (getInstance && typeof getInstance === 'function') {
            getInstance(art);
        }

        return () => {
            if (art && art.destroy) {
                art.destroy(false);
            }
        };
    }, []);

    return <div
        ref={artRef}
        className={styles.container}
        {...divProp}
    ></div>;
}

export default App
